<?php

/**
 * Created by PhpStorm.
 * User: zuoa
 * Date: 2016/11/23 0023
 * Time: 11:02
 */
class Wx extends Y_Controller
{
    private $appid = 'wxb142d225b763c251';
    private $appsecret = '8a042b764ad733bfc93a7c6d4e302e01';

    public function __construct()
    {
        parent::__construct();
        $this->load->model('user_model');
        $this->load->model('record_model');
        $this->load->model('dept_model');
        $this->load->model('preset_model');
        $this->load->model('violation_model');
        $this->load->model('question_model');
        $this->load->model('employee_model');
        $this->load->model('position_model');

        $this->load->helper('cookie');
        $this->load->helper('url');

        $this->load->library('session');
        $this->load->library('jssdk', array("appid" => $this->appid, "appsecret" => $this->appsecret));
    }

    public function index()
    {
        $code = $this->input->get("code");
        if ($code == "") {
            redirect('https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $this->appid . '&redirect_uri=http%3A%2F%2Fsghd.yuy.im%2Fwx&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect');
            return;
        }

        $token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $this->appid . '&secret=' . $this->appsecret . '&code=' . $code . '&grant_type=authorization_code';
        $token = json_decode(file_get_contents($token_url));
        $user = $this->user_model->get_user($token->openid);
        if ($token->openid == "") {
            redirect('https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $this->appid . '&redirect_uri=http%3A%2F%2Fsghd.yuy.im%2Fwx&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect');
            return;
        }

        if ($user != null && $user->checked > 0) {
            $newdata = array(
                'openid' => $user->openid,
                'name' => $user->name,
                'department' => $user->department,
                "idcard" => $user->idcard,
                "phone" => $user->phone
            );

            $this->session->set_userdata($newdata);

            redirect('/wx/sgcl');
        } else {
            $this->session->set_userdata('openid', $token->openid);
            redirect('/wx/register');
        }
    }

    /**
     * 绑定信息
     */
    public function register()
    {
        if ($this->is_post()) {
            $u = array(
                "openid" => $this->input->post("openid"),
                "name" => $this->input->post("name"),
                "department" => $this->input->post("department"),
                "idcard" => $this->input->post("idcard"),
                "phone" => $this->input->post("phone")
            );

            if ($this->preset_model->is_preset($this->input->post("idcard"), $this->input->post("name"))) {
                $u["checked"] = 1;
            }


            $this->user_model->upsert($u);
            $user = $this->user_model->get_user($u["openid"]);
            $this->session->set_userdata($u);
            $this->response(200, "success", $user->checked);

        } else {
            $openid = $this->session->userdata('openid');;
            if (is_null($openid) || $openid == "") {
                redirect('/wx');
                return;
            }


            $user = $this->user_model->get_user($openid);
            $data["user"] = $user;
            $data["openid"] = $openid;
            $data["depts"] = $this->dept_model->get_depts();

            $this->load->view('wx/register', $data);
        }
    }

    /**
     * 事故处理
     */
    public function sgcl()
    {
        if ($this->is_post()) {

            $data = array(
                "lng" => $this->input->post("lng"),
                "lat" => $this->input->post("lat"),
                "related_info" => $this->input->post("related_info"),
                "openid" => $this->input->post("openid"),
                "department" => $this->input->post("department"),
                "type" => $this->input->post("type")
            );

            $result = $this->record_model->add_record($data);

            if (!$result) {
                $this->response(301, "事故单号已被使用，请确认事故单号是否正确", null);
            } else {
                $this->response(200, "success", null);
            }

        } else {
            $session = $this->session->userdata();
            $data["session"] = $session;
            $this->load->view('wx/sgcl', $data);
        }

    }

    public function signature()
    {
        $url = $this->input->get("url");
        $wxconfig = $this->jssdk->getSignPackage($url);
        echo json_encode($wxconfig);
    }

    public function signature_jsonp()
    {
        $url = $this->input->get("url");
        $wxconfig = $this->jssdk->getSignPackage($url);

        echo sprintf("wxcfg('%s', '%s', '%s', '%s');", $wxconfig["appId"], $wxconfig["nonceStr"], $wxconfig["timestamp"], $wxconfig["signature"]);

    }


    public function history()
    {
        $openid = $this->session->userdata('openid');;
        if (is_null($openid) || $openid == "") {
            redirect('/wx');
            return;
        }

        $result = $this->record_model->get_police_records($openid, 0, 20);
        $data["history_list"] = $result;
        $this->load->view('wx/history', $data);
    }

    /**
     * 违法登记
     */
    public function wzdj()
    {
        if ($this->is_post()) {
            $data = array(
                "lng" => $this->input->post("lng"),
                "lat" => $this->input->post("lat"),
                "police_id" => str_replace(" ", "", $this->input->post("pid")),
                "violator_idcard" => $this->input->post("violator_idcard"),
                "violator_name" => $this->input->post("violator_name"),
                "violator_tel" => $this->input->post("violator_tel"),
                "violation_code" => $this->input->post("violation_code")
            );

            $result = $this->violation_model->add_record($data);

            if (!$result) {
                $this->response(301, "数据库操作失败，请重试", null);
            } else {
                $history = $this->violation_model->get_records_by_violator($data["violator_idcard"]);
                $this->response(200, "success", $history);
            }
        } else {
            echo $this->config->item("cache_path");
            $qs = $this->question_model->get_random_questions();
            $arr = array();
            foreach ($qs as $q) {
                array_push($arr, $q["id"]);
            }
            $data['next'] = join('_', $arr);

            $codearr = $this->violation_model->get_code();
            $data['code'] = $codearr;

            $this->load->view('wx/wzdj', $data);
        }
    }

    public function wzjl($idcard)
    {
        $data['history'] = $this->violation_model->get_records_by_violator($idcard);
        $this->load->view('wx/wzjl', $data);
    }

    /**
     * 违法考试
     */
    public function wzks($next = '')
    {
        $n = explode("_", $next);
        if (!empty($n)) {
            $index = array_shift($n);
            if (!empty($index)) {
                $data['q'] = $this->question_model->get_question($index);
                $data['next'] = join('_', $n);
                $this->load->view('wx/wzks', $data);
            } else {

                $this->load->view('wx/msg_success');
            }
        }
    }

    public function bindemployee()
    {
        if ($this->is_post()) {
            $e = array(
                "openid" => $this->input->post("openid"),
                "name" => $this->input->post("name"),
                "card" => $this->input->post("card"),
                "tel" => $this->input->post("tel")
            );

            $this->employee_model->upsert($e);
            $this->session->set_userdata('e_openid', $this->input->post("openid"));

            $this->response(200);

        } else {
            $code = $this->input->get("code");
            if (empty($code)) {
                redirect('https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $this->appid . '&redirect_uri=http%3A%2F%2Fsghd.yuy.im%2Fwx%2Fbindemployee&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect');
                return;
            }
            $token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $this->appid . '&secret=' . $this->appsecret . '&code=' . $code . '&grant_type=authorization_code';
            $token = json_decode(file_get_contents($token_url));
            if (!$token->openid) {
                redirect('https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $this->appid . '&redirect_uri=http%3A%2F%2Fsghd.yuy.im%2Fwx%2Fbindemployee&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect');
                return;
            }
            $employee = $this->employee_model->get_employee($token->openid);
            if ($employee != null) {
                $this->session->set_userdata('e_openid', $token->openid);
                redirect("/wx/position");
            } else {
                $data["openid"] = $token->openid;
                $this->load->view('wx/bind_employee', $data);
            }

        }
    }

    public function position()
    {
        if ($this->is_post()) {
            $r = array(
                "openid" => $this->session->userdata("e_openid"),
                "lng" => $this->input->post("lng"),
                "lat" => $this->input->post("lat")
            );

            $this->position_model->add_record($r);
            $this->response(200, $this->position_model->is_in_area($r["lng"], $r["lat"]));

        } else {
            $openid = $this->session->userdata("e_openid");
            if (empty($openid)) {
                redirect("/wx/bindemployee");
            } else {


                $data["first_record"] = $this->position_model->get_today_first_record($openid);
                $data["last_record"] = $this->position_model->get_today_last_record($openid);
                $this->load->view('wx/position', $data);
            }
        }
    }


}